import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import moment from 'moment';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Table,
  Form,
  Spin,
  Modal,
  Button,
  message,
  Tabs,
  DatePicker,
  Select,
  Input,
  Tooltip,
  Tag,
  Pagination
} from 'antd';
import styles from './versionb.less';
import saoba from '@/assets/icons/saoba.png';
import fanhui from '@/assets/icons/fanhui.png';
import lajixiang from '@/assets/icons/lajixiang.png';
import deleteimg from '@/assets/buttonimg/delete.png';
import riqi from '@/assets/versionMaintenance/riqi.png';
import qkls from '@/assets/versionMaintenance/qkls.png';
import dc from '@/assets/versionMaintenance/dc.png';
import moreImg from '@/assets/knowledge/more.png';
import tablea from '@/assets/versionMaintenance/tablea.png';
import table2 from '@/assets/versionMaintenance/table2.png';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const FormItem = Form.Item;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_7h7eh1i4s56.js', // 在 iconfont.cn 上生成
});

class Versionb extends Component {
  constructor(props) {
    super(props);
    this.state = {
      total: '',
      dataSource: [],
      pageSize: 10,
      page: 1,
      login: false,
      query: '',
    };
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (query, page, limit, from, to) => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'versiontwo/fetch',
        payload: { robotId: currentUser.robotId, query, page, limit, from, to },
        callback: res => {
          console.log('列表数据', res);
          let temp = res.list;
          temp.map((item, index) => (item['key'] = index));
          this.setState({
            dataSource: temp,
            total: res.total,
            login: false,
          });
        },
      });
    });
  };

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
  };

  componentWillMount() {
    let beginTimea = moment(new Date())
      .subtract(7, 'days')
      .format('YYYY-MM-DD');
    let overTimea = moment(new Date()).format('YYYY-MM-DD');
    this.setState({
      beginTime: beginTimea,
      overTime: overTimea,
    });
    console.log(overTimea, beginTimea);
  }

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState(
      {
        beginTime: dateString[0].replace(/\//g, '-'),
        overTime: dateString[1].replace(/\//g, '-'),
      },
      () => {
        const { beginTime, overTime, page, pageSize, query } = this.state; // query,page,limit,from,to
        console.log(date, this.state.beginTime);
        this.fetch(query, page, pageSize, beginTime, overTime);
      }
    );
    let a = dateString[0].replace(/\//g, '-');
    let b = dateString[1].replace(/\//g, '-');
  };

  answerDetail = () => {
    let user = this.userInfo();
    console.log(user);
    this.setState(
      {
        query: user.inputA,
        page: 1,
      },
      () => {
        const { beginTime, overTime, page, pageSize, query } = this.state; // query,page,limit,from,to
        this.fetch(query, page, pageSize, beginTime, overTime);
      }
    );
  };

  dateZdy = () => {
    return <img style={{ cursor: 'pointer' }} src={riqi} />;
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { beginTime, overTime, page, pageSize, query } = this.state; // query,page,limit,from,to
    this.fetch(query, page, pageSize, beginTime, overTime);
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <div className={styles.backgroundp}>

            <div style={{ marginBottom: 20 }} className={styles.fromColumn}>
              <span style={{marginLeft:14}} className="zdyButtonQk">
                <img
                  onClick={this.clearHistory}
                  style={{ cursor: 'pointer', marginTop: 5 }}
                  src={qkls}
                />
              </span>

              <div style={{ float: 'right',marginRight:12 }}>
                <Form className={styles.buttonA} layout="inline">
                  <FormItem className="zdyinput">
                    <RangePicker
                      suffixIcon={this.dateZdy()}
                      onChange={this.onChange}
                      style={{ height: 50, width: 312 }}
                      defaultValue={[
                        moment(this.state.beginTime, dateFormat),
                        moment(this.state.overTime, dateFormat),
                      ]}
                      format={dateFormat}
                    />
                  </FormItem>
                  <FormItem className="zdyinputa">
                    {getFieldDecorator('inputA', {
                      initialValue: '',
                    })(
                      // <Input
                      //   onPressEnter={this.answerDetail}
                      //   placeholder="请输入搜索内容"
                      //   style={{ height: 54, width: 312 }}
                      // />
                      <Search
                        // allowClear
                        // suffix = {this.dateZdya()}
                        placeholder="请输入搜索内容"
                        onSearch={value => {
                          console.log(value);
                          this.setState(
                            {
                              query: value,
                              page: 1,
                            },
                            () => {
                              const { beginTime, overTime, page, pageSize, query } = this.state; // query,page,limit,from,to
                              this.fetch(query, page, pageSize, beginTime, overTime);
                            }
                          );
                        }}
                        style={{ height: 50, width: 312 }}
                      />
                    )}
                  </FormItem>
                </Form>
              </div>
            </div>

            {this.lessdata()}
            <div>
        <Pagination
                style={{ textAlign: 'center', marginTop: 20}}
                total={this.state.total}
                pageSize={this.state.pageSize} // 显示几条一页
                current={this.state.page} // 当前页
                showSizeChanger={true} // 是否显示可以设置几条一页的选项
                showQuickJumper={true}
                onChange={this.onChangeA}
                onShowSizeChange={this.onShowSizeChangeA}
                showTotal={() => `共 ${this.state.total} 条`}
              />
        </div>
        </div>
        
      </div>
    );
  }

  lessdata = () => {
    const { selectedRowKeys } = this.state;
    // 多选
    const columns = [
      {
        title: '问题',
        width: 'calc(25vw)',
        dataIndex: 'question',
        render: question => {
          return (
            <div
              style={{ maxWidth: 400, wordWrap: 'break-word' }}
              dangerouslySetInnerHTML={{ __html: question }}
            />
          );
        },
      },
      // {
      //   title: '回答',
      //   width: 'calc(15vw)',
      //   dataIndex: 'answerCount'
      // },
      {
        title: '所属分类',
        width: 'calc(20vw)',
        dataIndex: 'category',
      },
      {
        title: '删除时间',
        dataIndex: 'updateTime',
        width: 'calc(20vw)',
        align: 'center',
        render: dataIndex => {
          return moment(Number(dataIndex)).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        // width: 'calc(15vw)',
        width: '250px',
        align: 'center',
        render: (text, row) => {
          return (
            <div>
              <div className={styles.tool}>
                <img  onClick={() => this.newlyAdded(row)} src={tablea} />
                <img  onClick={() => this.ignore(row)} style={{ marginLeft: 15 }} src={table2} />
              </div>
              <img src={moreImg} className={styles.more} />
            </div>
          );
        },
      },
    ];
    return (
      <div>
        <Spin  spinning={this.state.login}>
          <div style={{padding:'0px 20px'}} className={styles.dabj}>
          <div className={styles.border}>
          <Table
            className="zdyTable"
            columns={columns}
            dataSource={this.state.dataSource} //数据
            pagination={false}
          />
          </div>
          </div>
        </Spin>
      </div>
    );
  };

  onChangeA = val => {
    // 页数选择
    console.log(val);
    this.setState({ page: val }, () => {
      const { beginTime, overTime, page, pageSize, query } = this.state;
      this.fetch(query, page, pageSize, beginTime, overTime);
    });
  };

  onShowSizeChangeA = (current, pageSize) => {
    console.log('1', current, '2', pageSize);
    this.setState({ pageSize: pageSize, page: current }, () => {
      const { beginTime, overTime, page, query } = this.state;
      this.fetch(query, page, pageSize, beginTime, overTime);
    });
  };

  newlyAdded = text => {
    console.log(text);
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'versiontwo/fetchb',
        payload: { id: text.id },
        callback: res => {
          console.log('列表数据', res);
          if (res.code === 0) {
            message['success'](`${res.msg}`);
            setTimeout(() => {
              const { beginTime, pageSize, overTime, page, query } = this.state;
              this.fetch(query, page, pageSize, beginTime, overTime);
            }, 1);
          }
          if (res.code !== 0) {
            message['error'](`${res.msg}`);
          }
        },
      });
    });
  };

  ignore = text => {
    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        console.log(text);
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'versiontwo/fetchc',
            payload: { qaId: text.id },
            callback: res => {
              console.log('列表数据', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`);
                setTimeout(() => {
                  const { beginTime, pageSize, overTime, page, query } = this.state;
                  this.fetch(query, page, pageSize, beginTime, overTime);
                }, 1);
              }
              if (res.code !== 0) {
                message['error'](`${res.msg}`);
              }
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel');
      },
    });
  };

  clearHistory = () => {
    Modal['confirm']({
      title: '清空回收站',
      content: '确定清空回收站所有内容吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'versiontwo/fetchd',
            payload: { robotId: currentUser.robotId },
            callback: res => {
              console.log('列表数据', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`);
                setTimeout(() => {
                  const { beginTime, pageSize, overTime, page, query } = this.state;
                  this.fetch('', page, pageSize, beginTime, overTime);
                }, 1);
              }
              if (res.code !== 0) {
                message['error'](`${res.msg}`);
              }
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel');
      },
    });
  };
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(Versionb));
